package hk.linkcredit.common.rocketmq.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;

public class RocketMqUtils {
    public static final String BEAN_NAME = "beanName";
    public static final String MSG_ID = "msgId";
    public static final String BIZ_ID = "bizId";
    /**
     * 发送事务消息
     * @param rocketMQTemplate 自动装配的rocketMQTemplate
     * @param topic 主题+tag
     * @param msg 消息内容
     * @param msgId 消息唯一id
     * @param bizId 业务唯一id
     * @param beanName 实现了ITransactionHandler接口的beanName，spring默认为类名并且首字母小写
     * @param obj 事务处理所需的参数
     * @return
     */
    public static TransactionSendResult sendMessageInTransaction(RocketMQTemplate rocketMQTemplate, String topic, String msg, String msgId, String bizId, String beanName, Object obj){
        assert StringUtils.isNotEmpty(topic);
        assert StringUtils.isNotEmpty(msg);
        assert StringUtils.isNotEmpty(msgId);
        assert StringUtils.isNotEmpty(bizId);
        assert StringUtils.isNotEmpty(beanName);
        assert obj!=null;
        return rocketMQTemplate.sendMessageInTransaction(
                topic,
                MessageBuilder.withPayload(msg)
                        .setHeader(BEAN_NAME,beanName)
                        .setHeader(MSG_ID, msgId)
                        .setHeader(BIZ_ID, bizId)
                        .build(),
                obj
        );
    }


}
